package com.aviation.sell_ticket.tool;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Map;

@Component
public class SendMail {

    @Value("${spring.mail.username}")
    private String mailUsername;

    @Resource
    private JavaMailSender javaMailSender;

    @Resource
    private TemplateEngine templateEngine;

    @Async
    public void sendVerificationCode(String to, String verificationCode) {
        try {
            MimeMessage message = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setSubject("[坎巴拉航空计划]收到验证码");
            helper.setFrom(mailUsername);
            helper.setTo(to);
            helper.setSentDate(new Date());
            Context context = new Context();
            context.setVariable("verificationCode", verificationCode);
            context.setVariable("username", to);
            String text = templateEngine.process("mail.html", context);
            helper.setText(text, true);
            javaMailSender.send(message);
        }catch (Exception e){
            System.out.println(e);
        }
    }

}
